package com.future;

/**
 * Description:
 *
 * @author weiruibai.vendor
 * Date: 2021/12/9 11:21
 */
public class Solution_2 {

    public static void main(String[] args) {
        ListNode head1 = new ListNode(9);
        head1.next = new ListNode(9);
        head1.next.next = new ListNode(1);

        ListNode head2 = new ListNode(1);
        ListNode ans = addTwoNumbers(head1, head2);
        print(ans);
    }

    private static void print(ListNode head) {
        while (head != null) {
            System.out.print(head.val + " ");
            head = head.next;
        }
    }

    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode ans = new ListNode(-1);
        ListNode op = ans;
        boolean flag = false;
        int val = 0;
        while (l1 != null && l2 != null) {
            val = l1.val + l2.val;
            if (flag) {
                val++;
                flag = false;
            }
            if (val >= 10) {
                flag = true;
                val = val - 10;
            }
            l1 = l1.next;
            l2 = l2.next;
            op.next = new ListNode(val);
            op = op.next;
        }
        while (l1 != null) {
            val = l1.val;
            if (flag) {
                val++;
                flag = false;
            }
            if (val >= 10) {
                val = val - 10;
                flag = true;
            }
            op.next = new ListNode(val);
            op = op.next;
            l1 = l1.next;
        }
        while (l2 != null) {
            val = l2.val;
            if (flag) {
                val++;
                flag = false;
            }
            if (val >= 10) {
                val = val - 10;
                flag = true;
            }
            op.next = new ListNode(val);
            op = op.next;
            l2 = l2.next;
        }
        if (flag) {
            op.next = new ListNode(1);
        }
        return ans.next;
    }


    public static class ListNode {
        int val;
        ListNode next;

        public ListNode() {
        }

        public ListNode(int val) {
            this.val = val;
        }

        public ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}
